<?php

App::import('Vendor', 'twitter', array('file'=>'twitter'.DS.'TwitterApi.php'));
App::import('Vendor', 'lib', array('file'=>'lib'.DS.'utility.php'));

class UsersController extends AppController{
	var $name = "Users";
	var $uses = array("Status","User","Campus",'Category',"Favorite");
	var $helpers = array('javascript','form','html'); 
	
	var $components = array('Session','Cookie','RequestHandler','Twitter','Fauth');
	/*
	 * datahashビューに表示させるデータ
	 * user => ログインしたユーザー
	 * twitter_user => Twitterから取ってきたユーザー 
	 */
	var $datahash = array();
	var $consumer_key = "si2UvZAvFqJULHPSReXjA";
	var $consumer_secret = "qn4YEDOFUPYTwWkexlk2SdDYcW7zAvRaPNSR5GJ5k";
	var $twitterApi = null;
  	//beforeFilterにログインしなくても良いactionを指定
  	function beforeFilter() {
  		$this->layout = "default";
		$this->Fauth->allow(array('auth_twitter','callback'));
		
		// セッションまたはクッキーにユーザーIDがあるとき
		if($this->Fauth->isAuth()){
			$this->datahash['login_user'] = $this->Fauth->user();
		}
		// セッションまたはクッキーにユーザーIDがないとき
		else{
			$this->datahash['login_user'] = array();
			if(!$this->Fauth->isAllowAction()){
				// 
				if($this->Fauth->canmove()){
					$this->redirect('../users/login/');
				}
			}
		}

		if(!empty($this->datahash['login_user']['User']['id'])){
			//TwitterApiの作成
			$this->twitterApi = new TwitterApi(
						$this->consumer_key,
						$this->consumer_secret,
						$this->datahash['login_user']['User']['access_token_key'],
						$this->datahash['login_user']['User']['access_token_secret']
			);
		}
		//まだ認証してない&&セッションが保存されていない
		if(!empty($this->datahash['login_user']['User']['id']) && !$this->Session->check('twitter_uesr')){	
			// ユーザーIDがあるときはindexに、ないときはログイン画面に遷移
			$this->datahash['twitter_user'] = $this->twitterApi->showUser(array('id' => $this->datahash['login_user']['User']['id']));//twitterのユーザー情報を取得
			$this->Session->write('twitter_user',$this->datahash['twitter_user']);	//APIが勿体ないのでSESSIONに保存
		}else if($this->Session->check('twitter_user')){
			$this->datahash['twitter_user'] = $this->Session->read('twitter_user');
		}
				
		///Ajaxの共通処理
		//アクションにajaxが入っていたら実行
		if( $this->RequestHandler->isAjax() && strstr($this->action,'ajax')){
			Configure::write('debug', 0);
			$this->layout = "";
			$this->autoRender = false;
			$this->RequestHandler->setContent('json');
			$this->RequestHandler->respondAs('application/json; charset=UTF-8');
		}
		parent::beforeFilter();
	}
	/*
	 * ビューが呼ばれる前のコールバック
	 */
	function beforeRender(){
		$this->set('datahash',$this->datahash);
		parent::beforeRender();
	}
	/*
	 * Twitterの認証 
	 */
	function auth_twitter(){
		$this->autoRender = false;
		$this->layout = "";
		$callbackUrl = FULL_BASE_URL.$this->webroot.'users/callback/';//認証後ここのアドレスに返ってくるよ
		TwitterApi::RequestToken($this->consumer_key, $this->consumer_secret, $callbackUrl);
	}
	
	/*
	 * 認証後のコールバック関数 
	 */
	function callback(){
		$this->autoRender = false;
		$this->layout = "";
		$access_token = TwitterApi::AccessToken($this->consumer_key, $this->consumer_secret);
		
		$this->datahash['login_user']['User']['access_token_key'] = $access_token->key;
		$this->datahash['login_user']['User']['access_token_secret'] =$access_token->secret;
		$this->datahash['login_user']['User']['id'] = $access_token->user_id;
		$this->datahash['login_user']['User']['name'] = $access_token->screen_name;
		if(empty($access_token->key) || !$this->User->save($this->datahash['login_user']['User'])){
        	$this->Session->setFlash("Twitterの認証に失敗しました");
        }else{
			$this->Session->setFlash("Twitterの認証に成功しました");
			if(!empty($access_token->user_id)){
				// セッション保存			
				$this->Session->write('user_id',$access_token->user_id);
				// クッキー保存
				$this->Cookie->write('user_id',$access_token->user_id);
			}	
		}
		$this->redirect('../users/index/');
	}
	function setting($campusId = null){
		
		// ユーザー取得
		
		$user = $this->datahash['login_user']['User'];
		$user['campus_id'] = $campusId;
		
		if($this->User->save($user)){
			$this->Session->setFlash("キャンパス情報の登録に成功しました");
		}else{
			$this->Session->setFlash("キャンパス情報の登録に失敗しました");
		}
		$this->redirect('../users/index/');
	}
	
	function login(){
		//$this->layout = "default";
		
/*		App::import('Core','Sanitize');
		if(isset($_GET['campus_id'])){
			$this->datahash['campus'] = $this->Campus->findById(Sanitize::escape($_GET['campus_id']));
		}
		if(!empty($user)){
			$this->redirect('../users/index/');
		}
 */ 
	}

	function logout(){
		$this->Cookie->destroy();	//クッキーを破棄		
		$this->Session->destroy();	//セッションを破棄
    	$this->redirect('../users/login/');
    }

	function index(){
		$this->layout = "default";
		$this->datahash['lists'] = $this->twitterApi->getAllList(array('user_id'=>$this->datahash['login_user']['User']['id']));
		$campusId = $this->datahash['login_user']['User']['campus_id'];
		$univData = $this->Campus->findById($campusId);
		$this->set('univData',$univData);
	}

	function frexi(){
		$this->layout = "default";
		
		$categoryData = $this->Category->find("all");
		$category = array();
		foreach($categoryData as $key => $val){
			$category[$val['Category']['id']] = $val['Category']['name'];			
		}
		$category['0'] = "すべて";
		$this->datahash['category'] = $category;
	}
	
	function profile(){
		$this->datahash['ranking'] = $this->Favorite->getMoreFavoriteSutatues(3);
		foreach($this->datahash['ranking'] as $key => $val){
			if(!empty($val['User']['name'])){
				$this->datahash['ranking'][$key]['TwitterUser'] = $this->Twitter->getTwitterUser($val);
			}
		}
		$this->Status->recursive = 2;	//アドレスもくっつける
		$myStatus = $this->Status->getLatest($this->datahash['login_user']['User']['id']);
		$this->datahash['nearest'] = $this->Status->findMostNearest($myStatus['Location']['lat'], $myStatus['Location']['lng'], $this->datahash['login_user']['User']['twitter_user_id']);
		$this->datahash['mytweet'] = $myStatus;
		//print_r($myStatus);exit();
		$this->datahash['nearest']['TwitterUser'] = $this->Twitter->getTwitterUser($this->datahash['nearest']);
		$this->datahash['mytweet']['TwitterUser'] = $this->Twitter->getTwitterUser($this->datahash['mytweet']);
		
	}

	function followers(){
		$this->layout = "dialog";
		$this->set('title_for_layout', "フォロワー");
	}

	function friends(){
		$this->layout = "dialog";
		$this->set('title_for_layout', "フォロー");
	}
	
	function tweets(){
		$this->layout = "dialog";
		$this->set('title_for_layout', "ツイート");
	}
	
	function edit(){
		if (!empty($this->data['User'])) {
			$this->log($this->data['User'],LOG_DEBUG);
			//$this->User->create();
        	if(!$this->User->save($this->data['User'])){
        		$this->Session->setFlash("登録情報の変更に失敗しました");
        	}else{
        		$this->Session->setFlash("登録情報を変更しました");
        	}
        	$this->redirect('../users/index');
		} else {
			$user = $this->User->findById($this->datahash['login_user']['User']['id']);
			$frexi_tag = $user['User']['use_frexi_tag'];
			$location_information = $user['User']['use_location_information'];
			$this->set('frexi_tag',$frexi_tag);
			$this->set('location_information',$location_information);
		}
		
	}
	
	function create(){
		if (!empty($this->data['User'])) {
        	$this->User->create();
        	if(!$this->User->save($this->data['User'])){
        		$this->Session->setFlash("ユーザーの登録に失敗しました");
        	}else{
        		$this->Session->setFlash("ユーザーの登録に成功しました");
        	}
        	$this->redirect('../users/login');
    	}
	}
	
	function remove(){
		
	}
	
	/*-------------------------------以下はAjax専用関数-------------------------------*/
	/*
	 * getLoginedUserのサーバー側
	 */
	function ajax_getLoginedUser(){
		if(!empty($this->datahash['login_user'])){
			$values = $this->datahash['login_user'];
		}else{
			$values = array('Error' => '1');
		}
		return json_encode($values);
		exit();
	}

}
?>